<template>
  <section class="space-y-4 pb-16">
    <!-- 搜索框 -->
    <div class="relative">
      <div class="relative">
        <input 
          v-model="searchKeyword"
          type="text" 
          placeholder="搜索场站名称..."
          class="w-full px-4 py-3 pl-10 border border-gray-200 rounded-lg bg-white/80 backdrop-blur focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent text-sm"
          @input="handleSearch"
        >
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m21 21-6-6m2-5a7 7 0 1 1-14 0 7 7 0 0 1 14 0z"/>
        </svg>
      </div>
    </div>
    
    <div class="flex items-center justify-between">
      <div class="relative">
        <button @click="showStatusPicker = !showStatusPicker"
                class="inline-flex items-center gap-1 px-3 py-1.5 border border-gray-200 bg-white/80 backdrop-blur rounded-md text-sm text-gray-700 hover:bg-white shadow-sm">
          <span class="truncate max-w-[180px]">{{ selectedStatusLabel }}</span>
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-4 h-4 text-gray-500"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 9l6 6 6-6"/></svg>
        </button>
        <div v-if="showStatusPicker" class="absolute left-0 top-full mt-2 z-20 inline-block rounded-lg bg-white text-gray-900 shadow-lg ring-1 ring-black/5 overflow-hidden">
          <button v-for="opt in statusOptions" :key="opt.value" class="block text-left px-3 py-2 hover:bg-gray-50 text-sm whitespace-nowrap" @click="selectStatus(opt.value)">
            <span class="truncate max-w-[16rem]">{{ opt.label }}</span>
          </button>
        </div>
      </div>
      <!-- 场站排名入口（跳转到独立页面） -->
      <button @click="goToRanking" class="inline-flex items-center gap-1 text-sm font-medium text-brand-600 hover:text-brand-700">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 13h4v8H3v-8Zm7-6h4v14h-4V7Zm7 3h4v11h-4V10Z"/></svg>
        <span>场站排名</span>
      </button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="flex justify-center items-center py-8">
      <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-500"></div>
      <span class="ml-2 text-gray-600">加载中...</span>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="loadError" class="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
      <div class="flex flex-col items-center justify-center space-y-3">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-12 h-12 text-red-400">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"/>
        </svg>
        <div class="text-red-700 font-medium">加载失败</div>
        <div class="text-red-600 text-sm">{{ loadError }}</div>
        <button @click="loadStations" class="mt-2 px-4 py-2 bg-red-600 text-white rounded-md text-sm hover:bg-red-700 transition">
          重新加载
        </button>
      </div>
    </div>

    <div v-else class="space-y-3">
      <div v-if="displaySites.length === 0" class="bg-white rounded-lg p-8 shadow-sm border border-gray-100 text-center">
        <div class="flex flex-col items-center justify-center space-y-3">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-12 h-12 text-gray-300">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 2C13.1 2 14 2.9 14 4C14 5.1 13.1 6 12 6C10.9 6 10 5.1 10 4C10 2.9 10.9 2 12 2ZM21 9V7C21 5.9 20.1 5 19 5H5C3.9 5 3 5.9 3 7V9C3 10.1 3.9 11 5 11H19C20.1 11 21 10.1 21 9ZM5 13H7V21H5V13ZM9 13H11V21H9V13ZM13 13H15V21H13V13ZM17 13H19V21H17V13Z"/>
          </svg>
          <div class="text-gray-500 text-sm">暂无符合条件的场站</div>
          <div class="text-gray-400 text-xs">请尝试调整筛选条件</div>
        </div>
      </div>
      
      <div v-else v-for="s in displaySites" :key="s.stationId" class="relative rounded-2xl bg-white border-2 shadow-sm overflow-hidden hover:shadow-md transition" :class="statusConf(s).cardBorder">
        <div class="p-4">
          <div class="flex items-start justify-between gap-3">
            <div>
              <div class="text-xl font-semibold text-gray-900 tracking-tight">{{ s.stationName }}</div>
              <div class="mt-1 space-y-0.5 text-xs text-gray-600">
                <div>运营商：{{ s.operatorName || '未知' }}</div>
                <div>地址：{{ s.stationAddress }}</div>
              </div>
            </div>
            <div :class="['inline-flex flex-col items-center justify-center px-2 py-1 rounded-md border text-xs font-medium select-none leading-tight', statusConf(s).badge]">
              <span>{{ statusConf(s).top }}</span>
              <span>{{ statusConf(s).bottom }}</span>
            </div>
          </div>

          <div class="mt-3 grid grid-cols-4 gap-2 text-center">
            <div class="rounded-xl bg-emerald-50 p-2 text-center">
              <div class="w-full inline-flex items-center justify-center gap-0.5 text-[12px] sm:text-[13px] text-gray-700 whitespace-nowrap leading-none -ml-0.5">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="w-4 h-4 shrink-0 text-emerald-600" fill="currentColor">
                  <path d="M12 2l-4 8h4l-2 12 8-12h-4l2-8z"/>
                </svg>
                <span>总桩数</span>
              </div>
              <div class="mt-0.5 text-sm font-normal text-gray-900 whitespace-nowrap tracking-tight leading-tight">{{ s.pileCount || 0 }}</div>
            </div>
            <div class="rounded-xl bg-sky-50 p-2 text-center">
              <div class="w-full inline-flex items-center justify-center gap-0.5 text-[12px] sm:text-[13px] text-gray-700 whitespace-nowrap leading-none -ml-0.5">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="w-4 h-4 shrink-0 text-sky-600" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <circle cx="7" cy="7" r="2"/>
                  <circle cx="17" cy="17" r="2"/>
                  <line x1="6" y1="18" x2="18" y2="6"/>
                </svg>
                <span>分成比例</span>
              </div>
              <div class="mt-0.5 text-sm font-normal text-gray-900 whitespace-nowrap tracking-tight leading-tight">{{ s.shareRatio || '0%' }}</div>
            </div>
            <div class="rounded-xl bg-violet-50 p-2 text-center">
              <div class="w-full inline-flex items-center justify-center gap-0.5 text-[12px] sm:text-[13px] text-gray-700 whitespace-nowrap leading-none -ml-0.5">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="w-4 h-4 shrink-0 text-violet-600" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <rect x="3" y="4.5" width="18" height="16" rx="2"/>
                  <line x1="3" y1="8" x2="21" y2="8"/>
                  <polygon points="9,13 13,15 9,17"/>
                </svg>
                <span>开始日期</span>
              </div>
              <div class="mt-1 text-sm font-medium text-gray-900 whitespace-nowrap tracking-tight leading-tight">{{ s.startTime ? fmtDateInlineShort(s.startTime) : '未知' }}</div>
            </div>
            <div class="rounded-xl bg-amber-50 p-2 text-center">
              <div class="w-full inline-flex items-center justify-center gap-0.5 text-[12px] sm:text-[13px] text-gray-700 whitespace-nowrap leading-none -ml-0.5">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="w-4 h-4 shrink-0 text-amber-600" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <rect x="3" y="4.5" width="18" height="16" rx="2"/>
                  <line x1="3" y1="8" x2="21" y2="8"/>
                  <rect x="10" y="13" width="4" height="4" rx="1"/>
                </svg>
                <span>截止日期</span>
              </div>
              <div class="mt-1 text-sm font-medium text-gray-900 whitespace-nowrap tracking-tight leading-tight">{{ s.endTime ? fmtDateInlineShort(s.endTime) : '未知' }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载更多 -->
      <div class="text-center py-4">
        <button v-if="hasMore && displaySites.length > 0" @click="loadMore" 
                :disabled="loadMoreLoading"
                class="text-sm text-gray-600 hover:text-gray-900 px-4 py-2 border border-gray-200 rounded-lg hover:border-gray-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
          <span v-if="loadMoreLoading" class="flex items-center justify-center">
            <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-gray-700" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            加载中...
          </span>
          <span v-else>加载更多记录</span>
        </button>
        <div v-else-if="displaySites.length > 0" class="text-sm text-gray-500">没有更多记录了</div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { getFullStationList } from '../api/station'
import { getDictLabel, getDictOptions } from '../utils/dictionary'

const router = useRouter()

// 站点数据
const sites = ref([])
const loading = ref(false)
const loadMoreLoading = ref(false)
const searchKeyword = ref('')
const loadError = ref('') 
const hasMore = ref(true)
const lastId = ref('')

// 状态筛选
const filterStatus = ref('all')
const showStatusPicker = ref(false)

// 使用字典数据生成状态选项
const statusOptions = computed(() => {
  const dictOptions = getDictOptions('充电站运营状态')
  const options = [
    { value: 'all', label: '全部场站' }
  ]
  
  if (dictOptions.length > 0) {
    dictOptions.forEach(option => {
      options.push({
        value: option.value,
        label: option.label
      })
    })
  } else {
    console.warn('字典数据未加载，状态筛选将不可用')
  }
  
  return options
})

const selectedStatusLabel = computed(() => {
  if (filterStatus.value === 'all') return '全部场站'
  return getDictLabel('充电站运营状态', filterStatus.value) || '未知状态'
})

const selectStatus = (v) => { 
  filterStatus.value = v; 
  showStatusPicker.value = false
  // 状态筛选时重新加载数据
  loadStations(false)
}

// 搜索处理
const handleSearch = () => {
  // 使用防抖进行搜索，避免频繁请求
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    loadStations(false)
  }, 500)
}

// 搜索防抖
let searchTimeout = null
onBeforeUnmount(() => {
  clearTimeout(searchTimeout)
})

// 加载站点数据 - 添加防重复调用机制
let isLoadInProgress = false
const loadStations = async (isLoadMore = false) => {
  // 防止重复调用
  if (isLoadInProgress) {
    console.log('🔄 加载已在进行中，跳过重复调用')
    return
  }
  
  try {
    isLoadInProgress = true
    
    if (isLoadMore) {
      loadMoreLoading.value = true
    } else {
      loading.value = true
      // 重置分页状态
      sites.value = []
      lastId.value = ''
      hasMore.value = true
    }
    
    loadError.value = ''
    console.log('🚀 开始加载站点列表...', isLoadMore ? '加载更多' : '首次加载')
    
    // 构建请求参数
    const params = {
      lastId: isLoadMore ? lastId.value : '',
      status: filterStatus.value !== 'all' ? filterStatus.value : '',
      keyword: searchKeyword.value.trim()
    }
    
    console.log('📋 请求参数:', params)
    
    const response = await getFullStationList(params)
    console.log('📡 接口响应:', response)
    
    if (response.success) {
      const newSites = response.data?.list || []
      
      if (isLoadMore) {
        // 加载更多时，追加数据
        sites.value = [...sites.value, ...newSites]
      } else {
        // 首次加载时，替换数据
        sites.value = newSites
      }
      
      // 更新分页状态
      if (newSites.length > 0) {
        // 如果有数据返回，更新最后一条数据的ID
        lastId.value = newSites[newSites.length - 1].stationId
      }
      
      // 判断是否还有更多数据
      hasMore.value = newSites.length === 10 // 如果返回10条数据，说明可能还有更多
      
      console.log('✅ 站点列表加载成功，共', sites.value.length, '个站点，还有更多:', hasMore.value)
    } else {
      const errorMsg = response.message || '请求失败，请检查网络连接'
      loadError.value = errorMsg
      console.error('❌ 加载站点列表失败:', errorMsg)
      if (!isLoadMore) {
        sites.value = []
      }
    }
  } catch (error) {
    let errorMsg = '网络错误，请检查连接'
    if (error.message) {
      errorMsg = error.message
    }
    loadError.value = errorMsg
    console.error('❌ 加载站点列表异常:', error)
    if (!isLoadMore) {
      sites.value = []
    }
  } finally {
    if (isLoadMore) {
      loadMoreLoading.value = false
    } else {
      loading.value = false
    }
    isLoadInProgress = false
  }
}

// 加载更多数据
const loadMore = () => {
  if (loadMoreLoading.value) {
    return
  }
  // 无论hasMore是什么状态，都尝试加载更多数据
  loadStations(true)
}

const goToRanking = () => {
  router.push('/ranking')
}

// 点击外部区域关闭下拉菜单
const closePickerOnOutsideClick = (event) => {
  const pickerElement = event.target.closest('.relative')
  if (!pickerElement && showStatusPicker.value) {
    showStatusPicker.value = false
  }
}

// 监听点击事件 - 只调用一次
onMounted(() => {
  console.log('🎯 Sites组件挂载，开始加载数据')
  document.addEventListener('click', closePickerOnOutsideClick)
  loadStations()
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closePickerOnOutsideClick)
})

// 显示站点列表（直接使用后端返回的数据）
const displaySites = computed(() => {
  return sites.value || []
})

// 站点状态配置
const statusConf = (s) => {
  const status = s.status // 使用新的 status 字段
  const statusLabel = getDictLabel('充电站运营状态', status)
  
  // 如果没有字典数据或状态值，显示默认状态
  if (!status || !statusLabel) {
    return {
      top: '未知', bottom: '',
      dot: 'bg-gray-400',
      badge: 'bg-gray-100 text-gray-700 border-gray-200 shadow-xs',
      cardBorder: 'border-gray-200'
    }
  }
  
  // 根据字典值动态设置显示文本和样式
  if (status === '0') {
    return {
      top: statusLabel, bottom: '',
      dot: 'bg-gray-400',
      badge: 'bg-gray-100 text-gray-700 border-gray-200 shadow-xs',
      cardBorder: 'border-gray-200'
    }
  }
  
  // 默认正常运营状态
  return {
    top: statusLabel.length > 2 ? statusLabel.substring(0, 2) : statusLabel, 
    bottom: statusLabel.length > 2 ? statusLabel.substring(2) : '',
    dot: 'bg-emerald-500',
    badge: 'bg-emerald-100 text-emerald-800 border-emerald-200 shadow-xs',
    cardBorder: 'border-emerald-200'
  }
}

// 日期格式化函数
const fmtDate = (s) => {
  if (!s) return ''
  const [y, m, d] = String(s).split('-')
  return `${y}年${m}月${d}日`
}

const fmtDateInline = (s) => {
  if (!s) return ''
  const [y, m, d] = String(s).split('-')
  return `${y}.${m}.${d}`
}

const fmtDateInlineShort = (s) => {
  if (!s) return ''
  // 更短格式：YY.MM.DD，进一步减少溢出概率
  const [y, m, d] = String(s).split('-')
  return `${String(y).slice(2)}.${m}.${d}`
}
</script>